﻿<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">订单数据大盘</h1>
      <p class="page-subtitle">实时监控订单数据趋势和关键指标</p>
    </div>

    <!-- 时间筛选器 -->
    <div class="filter-section">
      <div class="filter-card">
        <div class="filter-item">
          <label>统计天数：</label>
          <el-select
            v-model="filterDays"
            @change="handleFilterChange"
            style="width: 120px"
          >
            <el-option label="今天" :value="1" />
            <el-option label="7天" :value="7" />
            <el-option label="14天" :value="14" />
            <el-option label="30天" :value="30" />
            <el-option label="90天" :value="90" />
          </el-select>
        </div>
        <div class="filter-item">
          <label>开始日期：</label>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilterChange"
            style="width: 160px"
          />
        </div>
        <div class="filter-item">
          <label>结束日期：</label>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilterChange"
            style="width: 160px"
          />
        </div>
        <el-button
          type="primary"
          @click="fetchDashboardData"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="metrics-grid">
      <div class="metric-card total-amount">
        <div class="metric-icon">
          <el-icon><Money /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">订单总金额</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.totalOrderAmount || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.totalOrderAmount || 0) }}
          </div>
        </div>
      </div>

      <div class="metric-card paid-amount">
        <div class="metric-icon">
          <el-icon><CreditCard /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">已付金额</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.paidOrderAmount || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.paidOrderAmount || 0) }}
          </div>
        </div>
      </div>

      <div class="metric-card order-count">
        <div class="metric-icon">
          <el-icon><Document /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">订单总数</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.orderCount || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.orderCount || 0) }} 单
          </div>
        </div>
      </div>

      <div class="metric-card paid-count">
        <div class="metric-icon">
          <el-icon><Check /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">已付订单</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.paidOrderCount || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.paidOrderCount || 0) }} 单
          </div>
        </div>
      </div>

      <div class="metric-card refund-amount">
        <div class="metric-icon">
          <el-icon><RefreshLeft /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">退款金额</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.refundAmount || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.refundAmount || 0) }}
          </div>
        </div>
      </div>

      <div class="metric-card product-sales">
        <div class="metric-icon">
          <el-icon><Box /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">商品销量</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.productSales || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{ formatNumber(dashboardData.average?.productSales || 0) }} 件
          </div>
        </div>
      </div>

      <div class="metric-card promotion-sales">
        <div class="metric-icon">
          <el-icon><Star /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">促销销量</div>
          <div class="metric-value">
            {{ formatNumber(dashboardData.total?.promotionProductSales || 0) }}
          </div>
          <div class="metric-subtitle">
            平均每日
            {{
              formatNumber(dashboardData.average?.promotionProductSales || 0)
            }}
            件
          </div>
        </div>
      </div>

      <div class="metric-card promotion-ratio">
        <div class="metric-icon">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-label">促销占比</div>
          <div class="metric-value">
            {{ formatPercent(dashboardData.average?.promotionOrderRatio || 0) }}
          </div>
          <div class="metric-subtitle">促销订单金额占比</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 订单金额趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">订单金额趋势</h3>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color total"></span>
              <span>订单总金额</span>
            </div>
            <div class="legend-item">
              <span class="legend-color paid"></span>
              <span>已付金额</span>
            </div>
          </div>
        </div>
        <div id="amount-trend-chart" class="chart-container"></div>
      </div>

      <!-- 订单数量趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">订单数量趋势</h3>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color total"></span>
              <span>订单总数</span>
            </div>
            <div class="legend-item">
              <span class="legend-color paid"></span>
              <span>已付订单</span>
            </div>
          </div>
        </div>
        <div id="count-trend-chart" class="chart-container"></div>
      </div>

      <!-- 商品销量趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">商品销量趋势</h3>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color total"></span>
              <span>总销量</span>
            </div>
            <div class="legend-item">
              <span class="legend-color promotion"></span>
              <span>促销销量</span>
            </div>
          </div>
        </div>
        <div id="sales-trend-chart" class="chart-container"></div>
      </div>

      <!-- 支付转化率图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">支付转化率</h3>
          <div class="chart-subtitle">已付订单数 / 总订单数</div>
        </div>
        <div id="conversion-chart" class="chart-container"></div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <div class="table-card">
        <div class="table-header">
          <h3 class="table-title">每日数据明细</h3>
          <div class="table-actions">
            <el-button @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
        <el-table
          :data="dashboardData.dailyStats || []"
          stripe
          border
          class="data-table"
          :loading="loading"
        >
          <el-table-column
            prop="date"
            label="日期"
            width="120"
            align="center"
          />
          <el-table-column label="订单总金额" width="140" align="right">
            <template #default="{ row }">
              <span class="amount-cell">{{
                formatNumber(row.totalOrderAmount)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已付金额" width="140" align="right">
            <template #default="{ row }">
              <span class="amount-cell paid">{{
                formatNumber(row.paidOrderAmount)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单总数" width="100" align="center">
            <template #default="{ row }">
              <span class="count-cell">{{ formatNumber(row.orderCount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已付订单" width="100" align="center">
            <template #default="{ row }">
              <span class="count-cell paid">{{
                formatNumber(row.paidOrderCount)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退款金额" width="140" align="right">
            <template #default="{ row }">
              <span class="amount-cell refund">{{
                formatNumber(row.refundAmount)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品销量" width="100" align="center">
            <template #default="{ row }">
              <span class="count-cell">{{
                formatNumber(row.productSales)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="促销销量" width="100" align="center">
            <template #default="{ row }">
              <span class="count-cell promotion">{{
                formatNumber(row.promotionProductSales)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="促销占比" width="100" align="center">
            <template #default="{ row }">
              <span class="percent-cell">{{
                formatPercent(row.promotionOrderRatio)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付转化率" width="120" align="center">
            <template #default="{ row }">
              <span class="percent-cell">
                {{
                  row.orderCount > 0
                    ? formatPercent((row.paidOrderCount / row.orderCount) * 100)
                    : "0%"
                }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";
import * as echarts from "echarts";
import {
  Refresh,
  Money,
  CreditCard,
  Document,
  Check,
  RefreshLeft,
  Box,
  Star,
  TrendCharts,
  Download,
} from "@element-plus/icons-vue";

// 接口类型定义
interface DashboardRequest {
  days?: number;
  startDate?: string;
  endDate?: string;
}

interface DailyStatVO {
  date: string;
  totalOrderAmount: number;
  paidOrderAmount: number;
  orderCount: number;
  paidOrderCount: number;
  refundAmount: number;
  productSales: number;
  promotionProductSales: number;
  promotionOrderRatio: number;
}

interface DashboardVO {
  dailyStats: DailyStatVO[];
  total: DailyStatVO;
  average: DailyStatVO;
}

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const filterDays = ref(1);
const startDate = ref("");
const endDate = ref("");
const dashboardData = ref<DashboardVO>({
  dailyStats: [],
  total: {
    date: "总计",
    totalOrderAmount: 0,
    paidOrderAmount: 0,
    orderCount: 0,
    paidOrderCount: 0,
    refundAmount: 0,
    productSales: 0,
    promotionProductSales: 0,
    promotionOrderRatio: 0,
  },
  average: {
    date: "平均",
    totalOrderAmount: 0,
    paidOrderAmount: 0,
    orderCount: 0,
    paidOrderCount: 0,
    refundAmount: 0,
    productSales: 0,
    promotionProductSales: 0,
    promotionOrderRatio: 0,
  },
});

// 图表实例
let amountTrendChart: any = null;
let countTrendChart: any = null;
let salesTrendChart: any = null;
let conversionChart: any = null;

// 格式化数字
const formatNumber = (value: number | string): string => {
  const num = Number(value);
  if (isNaN(num)) return "0";
  return num.toLocaleString();
};

// 格式化百分比
const formatPercent = (value: number | string): string => {
  const num = Number(value);
  if (isNaN(num)) return "0%";
  return `${num.toFixed(1)}%`;
};

// 获取仪表盘数据
const fetchDashboardData = async () => {
  loading.value = true;
  try {
    const requestData: DashboardRequest = {
      days: filterDays.value,
    };

    if (startDate.value) {
      requestData.startDate = startDate.value;
    }

    if (endDate.value) {
      requestData.endDate = endDate.value;
    }

    const response = await postWithAuth(
      "/internal/dashboard/order/summary",
      requestData
    );

    if (response.code === 0 && response.data) {
      dashboardData.value = response.data;
      await nextTick();
      renderCharts();
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    console.error("获取仪表盘数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理筛选器变化
const handleFilterChange = () => {
  fetchDashboardData();
};

// 渲染金额趋势图
const renderAmountTrendChart = () => {
  const dom = document.getElementById("amount-trend-chart");
  if (!dom) return;

  if (amountTrendChart) {
    amountTrendChart.dispose();
  }

  amountTrendChart = echarts.init(dom);

  const dates = dashboardData.value.dailyStats.map((item) => item.date);
  const totalAmounts = dashboardData.value.dailyStats.map(
    (item) => item.totalOrderAmount
  );
  const paidAmounts = dashboardData.value.dailyStats.map(
    (item) => item.paidOrderAmount
  );

  amountTrendChart.setOption({
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`;
        params.forEach((param: any) => {
          result += `${param.marker}${param.seriesName}: ${formatNumber(
            param.value
          )}<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: ["订单总金额", "已付金额"],
      top: 10,
    },
    grid: {
      left: 60,
      right: 30,
      top: 50,
      bottom: 30,
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#666",
        fontSize: 12,
        formatter: (value: number) => `${formatNumber(value)}`,
      },
      splitLine: {
        lineStyle: {
          color: "#f0f0f0",
        },
      },
    },
    series: [
      {
        name: "订单总金额",
        type: "line",
        data: totalAmounts,
        smooth: true,
        lineStyle: {
          color: "#409EFF",
          width: 3,
        },
        itemStyle: {
          color: "#409EFF",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.05)" },
            ],
          },
        },
      },
      {
        name: "已付金额",
        type: "line",
        data: paidAmounts,
        smooth: true,
        lineStyle: {
          color: "#67C23A",
          width: 3,
        },
        itemStyle: {
          color: "#67C23A",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
              { offset: 1, color: "rgba(103, 194, 58, 0.05)" },
            ],
          },
        },
      },
    ],
  });
};

// 渲染数量趋势图
const renderCountTrendChart = () => {
  const dom = document.getElementById("count-trend-chart");
  if (!dom) return;

  if (countTrendChart) {
    countTrendChart.dispose();
  }

  countTrendChart = echarts.init(dom);

  const dates = dashboardData.value.dailyStats.map((item) => item.date);
  const totalCounts = dashboardData.value.dailyStats.map(
    (item) => item.orderCount
  );
  const paidCounts = dashboardData.value.dailyStats.map(
    (item) => item.paidOrderCount
  );

  countTrendChart.setOption({
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`;
        params.forEach((param: any) => {
          result += `${param.marker}${param.seriesName}: ${formatNumber(
            param.value
          )}单<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: ["订单总数", "已付订单"],
      top: 10,
    },
    grid: {
      left: 60,
      right: 30,
      top: 50,
      bottom: 30,
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
      splitLine: {
        lineStyle: {
          color: "#f0f0f0",
        },
      },
    },
    series: [
      {
        name: "订单总数",
        type: "bar",
        data: totalCounts,
        itemStyle: {
          color: "#409EFF",
        },
      },
      {
        name: "已付订单",
        type: "bar",
        data: paidCounts,
        itemStyle: {
          color: "#67C23A",
        },
      },
    ],
  });
};

// 渲染销量趋势图
const renderSalesTrendChart = () => {
  const dom = document.getElementById("sales-trend-chart");
  if (!dom) return;

  if (salesTrendChart) {
    salesTrendChart.dispose();
  }

  salesTrendChart = echarts.init(dom);

  const dates = dashboardData.value.dailyStats.map((item) => item.date);
  const totalSales = dashboardData.value.dailyStats.map(
    (item) => item.productSales
  );
  const promotionSales = dashboardData.value.dailyStats.map(
    (item) => item.promotionProductSales
  );

  salesTrendChart.setOption({
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`;
        params.forEach((param: any) => {
          result += `${param.marker}${param.seriesName}: ${formatNumber(
            param.value
          )}件<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: ["总销量", "促销销量"],
      top: 10,
    },
    grid: {
      left: 60,
      right: 30,
      top: 50,
      bottom: 30,
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
      splitLine: {
        lineStyle: {
          color: "#f0f0f0",
        },
      },
    },
    series: [
      {
        name: "总销量",
        type: "line",
        data: totalSales,
        smooth: true,
        lineStyle: {
          color: "#E6A23C",
          width: 3,
        },
        itemStyle: {
          color: "#E6A23C",
        },
      },
      {
        name: "促销销量",
        type: "line",
        data: promotionSales,
        smooth: true,
        lineStyle: {
          color: "#F56C6C",
          width: 3,
        },
        itemStyle: {
          color: "#F56C6C",
        },
      },
    ],
  });
};

// 渲染转化率图
const renderConversionChart = () => {
  const dom = document.getElementById("conversion-chart");
  if (!dom) return;

  if (conversionChart) {
    conversionChart.dispose();
  }

  conversionChart = echarts.init(dom);

  const dates = dashboardData.value.dailyStats.map((item) => item.date);
  const conversionRates = dashboardData.value.dailyStats.map((item) => {
    return item.orderCount > 0
      ? (item.paidOrderCount / item.orderCount) * 100
      : 0;
  });

  conversionChart.setOption({
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        const param = params[0];
        return `${param.axisValue}<br/>${
          param.marker
        }支付转化率: ${formatPercent(param.value)}`;
      },
    },
    grid: {
      left: 60,
      right: 30,
      top: 30,
      bottom: 30,
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        color: "#666",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#666",
        fontSize: 12,
        formatter: (value: number) => `${value}%`,
      },
      splitLine: {
        lineStyle: {
          color: "#f0f0f0",
        },
      },
    },
    series: [
      {
        name: "支付转化率",
        type: "line",
        data: conversionRates,
        smooth: true,
        lineStyle: {
          color: "#909399",
          width: 3,
        },
        itemStyle: {
          color: "#909399",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(144, 147, 153, 0.3)" },
              { offset: 1, color: "rgba(144, 147, 153, 0.05)" },
            ],
          },
        },
      },
    ],
  });
};

// 渲染所有图表
const renderCharts = () => {
  renderAmountTrendChart();
  renderCountTrendChart();
  renderSalesTrendChart();
  renderConversionChart();
};

// 导出数据
const exportData = async () => {
  exportLoading.value = true;
  try {
    if (
      !dashboardData.value.dailyStats ||
      dashboardData.value.dailyStats.length === 0
    ) {
      ElMessage.warning("没有数据可导出");
      return;
    }

    // 构建CSV内容
    const csvContent = buildCsvContent();

    // 创建并下载文件
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");

    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);

      // 生成文件名（包含日期范围）
      const dateRange = getDateRangeForFilename();
      link.setAttribute("download", `订单数据大盘_${dateRange}.csv`);

      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      ElMessage.success("数据导出成功");
    }
  } catch (error) {
    console.error("导出数据失败:", error);
    ElMessage.error("导出失败");
  } finally {
    exportLoading.value = false;
  }
};

// 构建CSV内容
const buildCsvContent = (): string => {
  const csvLines: string[] = [];

  // 添加BOM以支持中文
  csvLines.push("\uFEFF");

  // 添加表头
  const headers = [
    "日期",
    "订单总金额",
    "已付金额",
    "订单总数",
    "已付订单",
    "退款金额",
    "商品销量",
    "促销销量",
    "促销占比(%)",
    "支付转化率(%)",
  ];
  csvLines.push(headers.join(","));

  // 添加数据行
  dashboardData.value.dailyStats.forEach((row) => {
    const csvLine = [
      escapeCsvField(row.date),
      escapeCsvField(formatNumberForCsv(row.totalOrderAmount)),
      escapeCsvField(formatNumberForCsv(row.paidOrderAmount)),
      escapeCsvField(formatNumberForCsv(row.orderCount)),
      escapeCsvField(formatNumberForCsv(row.paidOrderCount)),
      escapeCsvField(formatNumberForCsv(row.refundAmount)),
      escapeCsvField(formatNumberForCsv(row.productSales)),
      escapeCsvField(formatNumberForCsv(row.promotionProductSales)),
      escapeCsvField(formatPercentForCsv(row.promotionOrderRatio)),
      escapeCsvField(
        formatPercentForCsv(
          row.orderCount > 0 ? (row.paidOrderCount / row.orderCount) * 100 : 0
        )
      ),
    ];
    csvLines.push(csvLine.join(","));
  });

  // 添加汇总行
  if (dashboardData.value.total) {
    const total = dashboardData.value.total;
    csvLines.push(""); // 空行分隔
    const summaryLine = [
      "汇总",
      escapeCsvField(formatNumberForCsv(total.totalOrderAmount)),
      escapeCsvField(formatNumberForCsv(total.paidOrderAmount)),
      escapeCsvField(formatNumberForCsv(total.orderCount)),
      escapeCsvField(formatNumberForCsv(total.paidOrderCount)),
      escapeCsvField(formatNumberForCsv(total.refundAmount)),
      escapeCsvField(formatNumberForCsv(total.productSales)),
      escapeCsvField(formatNumberForCsv(total.promotionProductSales)),
      escapeCsvField(formatPercentForCsv(total.promotionOrderRatio)),
      escapeCsvField(
        formatPercentForCsv(
          total.orderCount > 0
            ? (total.paidOrderCount / total.orderCount) * 100
            : 0
        )
      ),
    ];
    csvLines.push(summaryLine.join(","));
  }

  // 添加平均值行
  if (dashboardData.value.average) {
    const average = dashboardData.value.average;
    const averageLine = [
      "平均",
      escapeCsvField(formatNumberForCsv(average.totalOrderAmount)),
      escapeCsvField(formatNumberForCsv(average.paidOrderAmount)),
      escapeCsvField(formatNumberForCsv(average.orderCount)),
      escapeCsvField(formatNumberForCsv(average.paidOrderCount)),
      escapeCsvField(formatNumberForCsv(average.refundAmount)),
      escapeCsvField(formatNumberForCsv(average.productSales)),
      escapeCsvField(formatNumberForCsv(average.promotionProductSales)),
      escapeCsvField(formatPercentForCsv(average.promotionOrderRatio)),
      escapeCsvField(
        formatPercentForCsv(
          average.orderCount > 0
            ? (average.paidOrderCount / average.orderCount) * 100
            : 0
        )
      ),
    ];
    csvLines.push(averageLine.join(","));
  }

  return csvLines.join("\n");
};

// CSV字段转义处理
const escapeCsvField = (field: any): string => {
  if (field === null || field === undefined) {
    return "";
  }

  const stringField = String(field);
  if (
    stringField.includes(",") ||
    stringField.includes("\n") ||
    stringField.includes('"')
  ) {
    return `"${stringField.replace(/"/g, '""')}"`;
  }

  return stringField;
};

// 格式化数字用于CSV（移除千分位分隔符）
const formatNumberForCsv = (value: number | string): string => {
  const num = Number(value);
  if (isNaN(num)) return "0";
  return num.toString();
};

// 格式化百分比用于CSV
const formatPercentForCsv = (value: number | string): string => {
  const num = Number(value);
  if (isNaN(num)) return "0";
  return num.toFixed(1);
};

// 获取文件名中的日期范围
const getDateRangeForFilename = (): string => {
  const now = new Date();
  const today = now.toISOString().split("T")[0];

  if (startDate.value && endDate.value) {
    return `${startDate.value}_${endDate.value}`;
  } else if (startDate.value) {
    return `${startDate.value}_${today}`;
  } else if (endDate.value) {
    return `开始_${endDate.value}`;
  } else {
    // 根据筛选天数生成日期范围
    const days = filterDays.value;
    if (days === 1) {
      return today;
    } else {
      const startDate = new Date(
        now.getTime() - (days - 1) * 24 * 60 * 60 * 1000
      );
      const startDateStr = startDate.toISOString().split("T")[0];
      return `${startDateStr}_${today}`;
    }
  }
};

// 组件挂载
onMounted(() => {
  fetchDashboardData();
});

// 组件卸载
onBeforeUnmount(() => {
  if (amountTrendChart) {
    amountTrendChart.dispose();
  }
  if (countTrendChart) {
    countTrendChart.dispose();
  }
  if (salesTrendChart) {
    salesTrendChart.dispose();
  }
  if (conversionChart) {
    conversionChart.dispose();
  }
});
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
  font-size: 16px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.metric-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.metric-card.total-amount .metric-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.metric-card.paid-amount .metric-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.metric-card.order-count .metric-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.metric-card.paid-count .metric-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.metric-card.refund-amount .metric-icon {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.metric-card.product-sales .metric-icon {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.metric-card.promotion-sales .metric-icon {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.metric-card.promotion-ratio .metric-icon {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.metric-content {
  flex: 1;
}

.metric-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
  font-weight: 500;
}

.metric-value {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 4px;
}

.metric-subtitle {
  font-size: 12px;
  color: #9ca3af;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.chart-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.chart-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.total {
  background: #409eff;
}

.legend-color.paid {
  background: #67c23a;
}

.legend-color.promotion {
  background: #f56c6c;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.table-section {
  margin-bottom: 24px;
}

.table-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.data-table {
  width: 100%;
}

.amount-cell {
  font-weight: 600;
  color: #1f2937;
}

.amount-cell.paid {
  color: #67c23a;
}

.amount-cell.refund {
  color: #f56c6c;
}

.count-cell {
  font-weight: 600;
  color: #1f2937;
}

.count-cell.paid {
  color: #67c23a;
}

.count-cell.promotion {
  color: #f56c6c;
}

.percent-cell {
  font-weight: 600;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .filter-card {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .filter-item {
    justify-content: space-between;
  }

  .metrics-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .metric-card {
    padding: 20px;
  }

  .metric-value {
    font-size: 20px;
  }

  .chart-card {
    padding: 20px;
  }

  .chart-container {
    height: 250px;
  }

  .table-card {
    padding: 20px;
  }

  .data-table {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .dashboard-container {
    padding: 12px;
  }

  .page-title {
    font-size: 20px;
  }

  .metric-card {
    padding: 16px;
  }

  .metric-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .metric-value {
    font-size: 18px;
  }

  .chart-card {
    padding: 16px;
  }

  .chart-container {
    height: 200px;
  }

  .table-card {
    padding: 16px;
  }
}
</style>
